package com.sankuai.inf.leaf.segment.dao.impl;

import com.sankuai.inf.leaf.segment.dao.UserMapper;
import com.sankuai.inf.leaf.segment.model.User;
import com.sankuai.inf.leaf.segment.dao.UserDao;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;

import javax.sql.DataSource;
import java.util.List;

/**
 * @author final
 * @description
 * @date 2019-09-10 11:12
 */
public class UserDaoImpl implements UserDao {
    SqlSessionFactory sqlSessionFactory;

    public UserDaoImpl(DataSource dataSource) {
        TransactionFactory transactionFactory = new JdbcTransactionFactory();
        Environment environment = new Environment("development", transactionFactory, dataSource);
        Configuration configuration = new Configuration(environment);
        configuration.addMapper(UserMapper.class);
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
    }
    @Override
    public User getUserByUserName(String username) {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        try {
            User result = sqlSession.selectOne("com.sankuai.inf.leaf.segment.dao.UserMapper.getUserByUserName", username);
            sqlSession.commit();
            return result;
        } finally {
            sqlSession.close();
        }
    }

    @Override
    public void insertUser(User user) {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        try {
            sqlSession.insert("com.sankuai.inf.leaf.segment.dao.UserMapper.insertUser", user);
            sqlSession.commit();
        } finally {
            sqlSession.close();
        }
    }

    @Override
    public List<User> listUser() {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        try {
            List<User> result = sqlSession.selectList("com.sankuai.inf.leaf.segment.dao.UserMapper.listUser");
            sqlSession.commit();
            return result;
        } finally {
            sqlSession.close();
        }
    }

    @Override
    public void updateUser(User user) {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        try {
            sqlSession.update("com.sankuai.inf.leaf.segment.dao.UserMapper.updateUser",user);
            sqlSession.commit();
        } finally {
            sqlSession.close();
        }
    }
}
